//
// Created by jiash on 05/01/2022.
//
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include "nbd_server.h"

/**
 * Print out a message about how to use nbd-server. Split out to a separate
 * function so that we can call it from multiple places
 */
void usage()
{
    printf("Usage: \n"
           "\t-p 10809 | --port=10809\n"
           "\t-e /home/xxx.iso | --export=/home/xxx.iso\n"
           "\t-v | --version\toutput the version and exit\n"
    );
}

/**
 * Parse the command line.
 *
 * @param argc the argc argument to main()
 * @param argv the argv argument to main()
 **/
SERVER *cmdline(int argc, char *const argv[])
{
    if (argc == 1) {
        usage();
        return NULL;
    }
    struct option long_options[] = {
        {"port",    optional_argument, NULL, 'p'},
        {"export",  optional_argument, NULL, 'e'},
        {"version", no_argument,       NULL, 'v'},
        {0, 0, 0, 0}
    };

    SERVER *serve = malloc(sizeof(SERVER));
    serve->virtstyle = VIRT_IPLIT;
    serve->servename = "";

    int index = 0;
    while (1) {
        int c = getopt_long(argc, argv, "p:e:v", long_options, NULL);
        if (c < 0)
            break;
        index++;

        switch (c) {
            case 'p':
                serve->net_port = optarg;
                printf("%s: [%d] net_port=%s\n", __func__, index, serve->net_port);
                break;
            case 'e':
                serve->exportname = optarg;
                printf("%s: [%d] exportname=%s\n", __func__, index, serve->exportname);
                break;
            case 'v':
                printf("This is nbd-server version v2.1.3\n");
                exit(EXIT_SUCCESS);
            default:
                usage();
                exit(EXIT_FAILURE);
        }
    }
    return serve;
}

int main(int argc, char *argv[])
{
    SERVER *serve = cmdline(argc, argv);
    if (serve == NULL)
        return EXIT_FAILURE;

    nbd_server(serve);

    free(serve);
    return EXIT_SUCCESS;
}

